<?php 
	
	class Agent_model extends CI_Model {
		
		 var $tblName = "qagent";
		 
		function __construct()
		{
			parent::__construct();
		}
		
		function save_skill_priority($POST)
		{	
			$uniqueids = $POST['ids'];
			
			$primary_skill 	= @$POST['primary_skill'];
			$primary_skill = $primary_skill[0];
			list($primary_skill, $primary_skill_id) = explode('~', $primary_skill);
			$primary_skill_id = (int)$primary_skill_id;
			
			if( count($uniqueids) > 0 ) 
			{
				foreach($uniqueids as $id)
				{
					$record = array( 
										'penalty' 		=> intval($POST['penalty'][$id]),
										'primary_skill' => addslashes($primary_skill)
									);
					$this->db->where('uniqueid', $id);				
					$this->db->update("queue_member_table", $record);
				}//end foreach 
			}
			
			DB_modification_logs("agent_priority");
		}
		
		/*function save_agent_skills($POST)
		{
			$agent = $POST['agent'];
			$agent = "Agent/".$agent;
	
			$skills			= @$POST['skills'];
			$primary_skill 	= @$POST['primary_skill'];
			$primary_skill = $primary_skill[0];
  			
			if( count($skills) > 0 ) 
			{
				//____________________ delete other skill _____________________
				$sql_delete = " DELETE from queue_member_table where membername = ".$this->db->escape($agent)."";		
				$this->db->query($sql_delete);			
				
				foreach($skills as $skill)
				{
					$record = array(
										'membername' 	=> addslashes($agent),
										'queue_name' 	=> addslashes($skill),
										'interface' 	=> addslashes($agent),
										'penalty' 		=> intval($POST['priority'][$skill]),
										'callerid' 		=> addslashes($POST['callerid'][$skill]),
										'queue_callerid'=> addslashes($POST['queue_callerid'][$skill]),
										'primary_skill' => addslashes($primary_skill)
									);
									
					$this->db->insert("queue_member_table", $record);
				}//end foreach 
			}
			DB_modification_logs("agent_skill");
		}//end function*/
		
		function save_agent_skills($POST)
		{
			$agent = $POST['agent'];
			$agent = "Agent/".$agent;
	
			$skills			= @$POST['skills'];
			$primary_skill 	= @$POST['primary_skill'];
			$primary_skill = $primary_skill[0];
  			
			if( count($skills) > 0 ) 
			{
				
				$skill_arr = array();
				foreach( $skills as $skill )
				{
					$skill_arr[] = "'$skill'";
				}
				$skill_str = implode(',', $skill_arr); 
				
				//____________________ delete other skill _____________________
				$sql_delete = " DELETE from queue_member_table where membername = ".$this->db->escape($agent)." AND queue_name <> 'dummy' AND queue_name NOT IN (".$skill_str.")";		
				$this->db->query($sql_delete);			
				
				foreach($skills as $skill)
				{
					$record = array(
											'membername' 	=> addslashes($agent),
											'queue_name' 	=> addslashes($skill),
											'interface' 	=> addslashes($agent),
											'penalty' 		=> intval($POST['priority'][$skill]),
											'callerid' 		=> addslashes($POST['callerid'][$skill]),
											'queue_callerid'=> addslashes($POST['queue_callerid'][$skill]),
											'primary_skill' => addslashes($primary_skill)
										);
					
					$where = " membername  = '".mysql_real_escape_string($agent)."' and queue_name = '".mysql_real_escape_string($skill)."' ";
					if( $this->common_model->record_exist("queue_member_table", $where)) // if same record exist, update it
					{
						$where = array(
										'membername' 	=> addslashes($agent),
										'queue_name' 	=> addslashes($skill)
										);
						$this->db->update("queue_member_table", $record, $where);	
					}
					else	// add new record
					{
						$this->db->insert("queue_member_table", $record);
					}
				}//end foreach 
			}
			DB_modification_logs("agent_skill");
		}//end function
		
		function getAgentSkills($membername)
		{
			$sql = "SELECT * FROM `queue_member_table` WHERE queue_name <> 'dummy' AND `membername`  LIKE '".mysql_real_escape_string($membername)."' order by primary_skill, queue_name";
			return $this->db->query($sql)->result(); 			
		}
		
		function getDetailByID($ext)
		{
		  $ext = (string)$ext;	
		/*  $sql = "SELECT
				q.agent_id,
				s.name as agent,
				s.username,
				s.secret,
				s.context,
				s.allow,
				q.First_Name,
				q.Last_Name,
				q.location
			FROM
				qagent q,
				sip_buddies s
			WHERE
				SUBSTRING_INDEX(q.agent, '/', - 1) = s. NAME
			AND q.agent_id = ".$id;*/
			
		   $sql = "SELECT 
						s.name as agent,
						s.username,
						s.secret,
						s.context,
						s.allow,
						a.full_name,
						a.location_name
					FROM 	
						sip_buddies s LEFT JOIN ccm_agents a ON SUBSTRING_INDEX(a.membername, '/', - 1) = s.name	
					WHERE
						s.name = '".$ext."'";
			
		  return $this->db->query($sql)->row_array();
		}
		

		function getListingData($GET, $start, $offset = 20)
		{
 			$where = ' WHERE 1=1 ';
			$where .= " AND qm.queue_name <> 'dummy' ";
			if( isset($GET['agent']) && trim($GET['agent']) != '' )
			{
				$where  .= " AND qm.membername LIKE '%".trim($this->db->escape($GET['agent']),"'")."%' ";	
			}
			if( isset($GET['name']) && trim($GET['name']) != '' )
			{
				$where  .= " AND concat(a.full_name) LIKE '%".trim($this->db->escape($GET['name']),"'")."%' ";	
			}
			if( isset($GET['skill']) && trim($GET['skill']) != '' )
			{
				$where  .= " AND qm.queue_name LIKE '".trim($this->db->escape($GET['skill']),"'")."' ";	
			}
			
			$LIMIT = "LIMIT $start ,  $offset ";
			//echo $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM " . $this->tblName . " {$where} order by first_name {$LIMIT} ";
			
			/*$sql = "SELECT SQL_CALC_FOUND_ROWS
							q.agent_id, q.agent, q.First_Name, q.Last_Name, GROUP_CONCAT(qm.queue_name) as 'skills' , qm.primary_skill  
						FROM qagent q INNER JOIN queue_member_table qm ON q.agent = qm.membername
						{$where}
					GROUP BY qm.membername order by q.First_Name {$LIMIT} ";*/
			$sql = "SELECT 
							SQL_CALC_FOUND_ROWS
							
							qm.membername, qm.interface, GROUP_CONCAT(qm.queue_name) as 'skills' , qm.primary_skill ,
							a.full_name
							
						FROM 
							queue_member_table qm LEFT JOIN ccm_agents a ON a.membername = qm.membername
						{$where}
					GROUP BY qm.membername order by a.full_name {$LIMIT} ";		
			
			
			$results = $this->db->query($sql)->result();	
			$total_record = $this->common_model->get_found_rows();
			
			foreach( $results as &$row)
			{
				$row->skills = $this->getAgentSkills_string($row->interface);	
			}
			
			return array('results' => $results, 'total_record' => $total_record);
		}
		
		function getAgentPrimarySkill($membername)
		{
			$sql = "SELECT * FROM `queue_member_table` WHERE `membername` LIKE '".mysql_real_escape_string($membername)."'";
			$result = $this->db->query($sql)->row_array(); 			
			if( isset($result['primary_skill']) ) {
				return $result['primary_skill'];	
			} else {
				return '';	
			}
		}
		
		
		function getAgentSkills_string($membername)
		{
			$sql = "SELECT GROUP_CONCAT(queue_name) as 'skills' FROM `queue_member_table` WHERE queue_name <> 'dummy' AND `membername` LIKE '".mysql_real_escape_string($membername)."' group by membername ";
			$result = $this->db->query($sql)->row_array(); 			
			if( isset($result['skills']) ) {
				return $result['skills'];	
			} else {
				return '';	
			}
		}
		
		
		function getAllagent()
		{
			//$sql = "select *, concat(First_Name, ' ', Last_Name) as agent_name from qagent ";
			//$sql = "select DISTINCT membername as agent , membername as agent_name from queue_member_table ORDER BY membername ASC";
			$sql = "select DISTINCT queue_member_table.membername as agent , ccm_agents.full_name as agent_name from queue_member_table LEFT JOIN ccm_agents ON queue_member_table.membername = ccm_agents.membername
					ORDER BY queue_member_table.membername ASC";
			return $this->db->query($sql)->result();
		}
		
		function updateSIPConfigFile($agent_data, $sip_file_path, $action="add")
		{
			$extension 	= $agent_data['agent'];
			$secret 	=  $agent_data['secret'];
			$type		= "friend";
			$host		= "host";
			$nat		= "no";
			$qualify	= "5000";
			$context	= $agent_data['context'];
			
			$str_to_write  = "\n[{$extension}]";
			$str_to_write .= "\nusername={$extension}";
			$str_to_write .= "\nsecret={$secret}";
			$str_to_write .= "\ntype={$type}";
			$str_to_write .= "\nhost={$host}";
			$str_to_write .= "\nnat={$nat}";
			$str_to_write .= "\nqualify={$qualify}";
			$str_to_write .= "\ncontext={$context}\n";	
			
			
			// open file for read
			$fh = fopen($sip_file_path, "r");
			if ($fh === false)
			{
				echo "Unable to open file for reading : DGSSIP.conf";
				exit;
			}
			$str = fread($fh, filesize($sip_file_path));
			fclose($fh);
			// end open file for read
			
			$str .= $str_to_write;
 			// open file for writing
			$fh = fopen($sip_file_path, "w");
			if($fh === false)
			{
				echo "Unable to open file for writing : DGSSIP.conf";
				exit;
			}
			
			if(!fwrite($fh, $str, strlen($str)))
			{
				echo "Unable to write file : DGSSIP.conf";
				exit;
			}
			
			fflush($fh);
			fclose($fh);
		}
		
		function updateAgentConfigFile($agent_data, $agent_file_path, $action)
		{
			$extension 	= $agent_data['agent'];
			$secret 	= $agent_data['secret'];
			$str_agent = "\nagent => $extension,$secret";										
			
			// open file for read
			$fh = fopen($agent_file_path, "r");
			if ($fh === false)
			{
				echo "Unable to open file for reading : agent.conf";
				exit;
			}
			$str = fread($fh, filesize($agent_file_path));
			fclose($fh);
			// end open file for read
			
 			$str .= $str_agent;
 			// open file for writing
			$fh = fopen($agent_file_path, "w");
			if($fh === false)
			{
				echo "Unable to open file for writing : agent.conf";
				exit;
			}
			
			if(!fwrite($fh, $str, strlen($str)))
			{
				echo "Unable to write file : agent.conf";
				exit;
			}
			
			fflush($fh);
			fclose($fh);
			
			
		}
		
		
		function updateConfigFile($agent_id, $action="add")
		{
			return '';
			$agent_data = $this->getDetailByID($agent_id);
 
  			$sip_file = $this->sip_file_path;
			$agent_file = $this->agent_file_path;
			
			$this->updateSIPConfigFile($agent_data, $sip_file, $action);
			$this->updateAgentConfigFile($agent_data, $agent_file, $action);
		}
		
		function write_log($content = 'test')
		{
			$log_file = $this->log_file_name;
			$f = fopen($log_file, 'a+');
			fwrite($f,$content,strlen($content));
			fclose($f);
		}
  }
?>